package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.support.v4.app.Fragment
import android.text.TextUtils
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.HomeFragmentContract
import com.ewzj.bigdata.mvp.contract.LogoContract
import com.ewzj.bigdata.mvp.contract.MineFragmentContract
import com.ewzj.bigdata.mvp.model.bean.UserBean
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.User
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.UiUtils
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import top.zibin.luban.Luban
import java.io.File
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class MineFragmentPresenter @Inject constructor(val mErrorHandler: RxErrorHandler, val application: Application, view: MineFragmentContract.View, model: MineFragmentContract.Model):BasePresenter<MineFragmentContract.Model,MineFragmentContract.View>(model,view){
    lateinit var userinfo:UserBean
    val context=(mRootView as Fragment).activity
    fun loadUserInfo(){
        mModel.loadUserInfo().compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<UserBean>>(mErrorHandler){
                    override fun onNext(t: BaseData<UserBean>) {
                        userinfo=t.data!!
                        if (!TextUtils.isEmpty(userinfo.avatar)){
                            mRootView.loadheadImg(Apputils.Utils.getImgUrl(userinfo.avatar))
                        }
                        if (!TextUtils.isEmpty(userinfo.bg_image)){
                            mRootView.setBgImg(Apputils.Utils.getImgUrl(userinfo.bg_image))
                        }
                        mRootView.setNickName(userinfo)
                    }

                })
    }

    fun uploadPic(filePath:String){
        Flowable.just(File(filePath))
                .observeOn(Schedulers.io())
                .map{
                    t ->  Luban.with(context).load(t).get()
                }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    t ->run{
                    mModel.upLoadPic(t).compose(RxUtils.applySchedulers(mRootView))
                            .subscribe({
                                t: BaseData<List<String>>? ->  mRootView.updateUserBg(t!!.data!![0])},
                                    { UiUtils.SnackbarText("上传失败")})
                }
                })

    }
}
